using GameKitUnity.Core;
using UnityEngine;
using UnityEngine.UI;

namespace OneGame.Gameplay.UI
{
    public class UIStateView : MonoBehaviour
    {
        [SerializeField]
        Image healthBar;

        CanvasGroup _canvasGroup;
        private RectTransform _rectTransform;
        private Camera _mainCamera;
        private readonly Vector2 _referenceResolution = new Vector2(1920, 1080);

        // PUBLIC
        public Transform StateTransform { get; set; }

        private void Awake()
        {
            _canvasGroup = GetComponent<CanvasGroup>();
            _rectTransform = GetComponent<RectTransform>();
        }

        private void Start()
        {
            _mainCamera = Camera.main;
        }

        public void Show(bool isShow)
        {
            if (isShow)
            {
                _canvasGroup.alpha = 1;
            }
            else
            {
                PoolManager.Instance.Release(gameObject);
            }
        }

        public void ShowHealth(int current, int max, int diff)
        {
            healthBar.fillAmount = (float)current / max;
        }

        private void LateUpdate()
        {
            var viewportPoint = _mainCamera.WorldToViewportPoint(StateTransform.position);
            var position = new Vector2(viewportPoint.x * _referenceResolution.x - _referenceResolution.x / 2, viewportPoint.y * _referenceResolution.y - _referenceResolution.y / 2);
            _rectTransform.anchoredPosition = position;
            var isVisible = viewportPoint is { z: > 0, x: > 0 and < 1, y: > 0 and < 1 };
            _canvasGroup.alpha = isVisible ? 1 : 0;
        }
    }
}